import concurrent.futures
import paho.mqtt.client as mqtt
import json
import time
import random
import threading
from utils.config import Config

class MQTTClient():
    def __init__(self):
        self.config = Config('./conf/config.ini')

        self.client = mqtt.Client(client_id=self.config.read_value('mqtt', 'client_id')+ str(random.randint(100000, 999999)))
        self.client.username_pw_set(self.config.read_value('mqtt', 'username'), self.config.read_value('mqtt', 'password'))
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.broker_address = self.config.read_value('mqtt', 'broker_address')
        self.port = int(self.config.read_value('mqtt', 'port'))

        self.received_messages = []  # 用于存储接收到的消息

        self.client.connect(self.broker_address, self.port, keepalive=60)
        self.client.loop_start()

    def __del__(self):
        self.client.disconnect()

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT broker")
        else:
            print(f"Connection failed with code {rc}")

    def on_message(self, client, userdata, message):
        payload = message.payload.decode('utf-8')
        # print(f"Received message '{payload}' on topic '{message.topic}'")
        # 存储接收到的消息
        self.received_messages.append({
            'topic': message.topic,
            'payload': payload,
            'timestamp': time.time()  # 可以根据需要存储时间戳
        })

    def publish_message(self, topic, payload):
        payload_str = json.dumps(payload, ensure_ascii=False)
        self.client.publish(topic, payload_str)

    def subscribe_topic(self, topic):
        self.client.subscribe(topic)

    def publish_multiple_messages(self, topic, payloads):
        for payload in payloads:
            payload_str = json.dumps(payload, ensure_ascii=False)
            self.client.publish(topic, payload_str)
            time.sleep(0.5)

    def concurrent_publish(self, topic, payloads):
        with concurrent.futures.ThreadPoolExecutor(max_workers=len(payloads)) as executor:
            futures = [executor.submit(self.publish_message, topic, payload) for payload in payloads]
            for future in concurrent.futures.as_completed(futures):
                try:
                    future.result()
                except Exception as exc:
                    print(f'Generated an exception: {exc}')

    def get_received_messages(self):
        return self.received_messages

# 示例用法
# if __name__ == "__main__":
#     mqtt_client = MQTTClient()
#     topic = "/link/objects_list"
#     # payloads = ["message1", "message2", "message3"]
#
#     mqtt_client.subscribe_topic(topic)
#
#     # mqtt_client.publish_multiple_messages(topic, payloads)
#     #
#     # mqtt_client.concurrent_publish(topic, payloads)
#
#     # 获取订阅的消息内容
#     while True:
#         received_messages = mqtt_client.get_received_messages()
#         if received_messages:
#             # print("Received messages:", received_messages)
#             data=json.loads(received_messages[0]['payload'])
#             # 提取速度数据
#             speeds = [obj["speed"] for obj in data["objects_list"]]
#
#             # 计算平均值
#             average_speed = sum(speeds) / len(speeds)
#
#             print("提取的速度数据:", speeds)
#             print("平均速度:", average_speed)
#             mqtt_client.received_messages = []
#         time.sleep(1)
